<?php 
namespace Home\Controller;

use Think\Controller;

class CommentController extends Controller{
    
    // 提交评论
    public function comment(){
        
        // 创建模型对象
        $comment_M = D('Comment');
        
        // 验证表单数据
        if (!$data = $comment_M->create()){
            $this->ajaxReturn(array('status'=>0,'msg'=>$comment_M->getError()));
            die;
        }
        
        // 设置评论时间
        $data['time'] = time();
        $data['username'] = session('user.username');
        
        // 添加数据到数据库
        $res = $comment_M->add($data);
        if ($res !== false){
            // 记录评论数
            M('blog')->where(array('id'=>I('post.blog_id')))->setInc('contact_count');
            
            // 设置任务进度
            $user_id = session('user.id');
            setFinish($user_id, 2);
            
            $this->ajaxReturn(array('status'=>1));
        }else{
            $this->ajaxReturn(array('status'=>0,'msg'=>'提交评论失败，请重试!'));
        }
    }
    
    // 提交回复
    public function commentBack(){
        
        // 创建模型对象
        $comment_M = D('Comment');
        
        // 验证表单数据
        if (!$data = $comment_M->create()){
            $this->ajaxReturn(array('status'=>0,'msg'=>$comment_M->getError()));
            die;
        }
        
        $user = session('user');
        
        if (empty($user)){
            $this->ajaxReturn(array('status'=>0,'msg'=>'请登录后评论'));
        }
        
        // 设置评论时间
        $data['time'] = time();
        $data['pid'] = I('get.comment_id');
        $data['username'] = $user['username'];
        
        M('comment')->where(array('id'=>I('get.comment_id')))->setField('is_last',0);
        
        // 添加数据到数据库
        $res = $comment_M->add($data);
        if ($res !== false){
            // 记录评论数
            M('blog')->where(array('id'=>I('post.blog_id')))->setInc('contact_count');
            
            // 设置任务进度
            $user_id = session('user.id');
            setFinish($user_id, 3);
            
            $this->ajaxReturn(array('status'=>1));
        }else{
            $this->ajaxReturn(array('status'=>0,'msg'=>'提交评论失败，请重试!'));
        }
    }
    
    // 顶
    public function good(){
        $com_id = I('post.id');
        $res = M('comment')->where(array('id'=>$com_id))->setInc('good_count');
        
        if ($res !== false){
            echo 1;die;
        }else {
            echo 0;die;
        }
    }
    
    // 踩
    public function bad(){
        $com_id = I('post.id');
        $res = M('comment')->where(array('id'=>$com_id))->setInc('bad_count');
        
        if ($res !== false){
            echo 1;die;
        }else {
            echo 0;die;
        }
    }
}

?>